package com.cat.DataStructure04;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/number-of-beautiful-integers-in-the-range/
 * @create 2025/11/25 10:59
 * @since JDK17
 */

public class Solution06 {
    int k, MAXN = 11;
    int[][][][] dp = new int[MAXN][MAXN][MAXN][MAXN];
    int dfs(char[]num, int i, int odd, int even, boolean isNum, int render, boolean free) {
        if (i == num.length) {
            return odd == even && isNum && render == 0 ? 1 : 0;
        }
        if (dp[i][odd][even][render] != -1) {
            return dp[i][odd][even][render];
        }
        int ans = 0, up = free ? 9 : num[i] - '0';
        if (!isNum) {
            ans = dfs(num, i + 1, odd, even,false, 0, true);
        }
        for (int j = isNum ? 0 : 1; j <= up; j++) {
            ans += dfs(num, i + 1, odd + j % 2, even + 1 - j % 2, true,(render * 10 + j) % k, free || (j < up));
        }
        dp[i][odd][even][render] = ans;
        return ans;
    }
    void build() {
        for (int i = 0; i < MAXN; i++) {
            for (int j = 0; j < MAXN; j++) {
                for (int k = 0; k < MAXN; k++) {
                    Arrays.fill(dp[i][j], -1);
                }
            }
        }
    }
    public int numberOfBeautifulIntegers(int low, int high, int k) {
        this.k = k;
        low--;
        build();
        int resL = dfs(String.valueOf(low).toCharArray(), 0, 0, 0, false, 0, false);
        build();
        int resH = dfs(String.valueOf(high).toCharArray(), 0, 0, 0, false, 0, false);
        return resH - resL;
    }
}
